from . import profile_blue
from flask import render_template,g,redirect,request,jsonify
from info.utils.commons import user_login_data
from info.response_code import error_map,RET
from info import db,constants
from info.utils.upload import rest_upload
import time
from info.models import Category,News

# 功能:个人关注的作者
@profile_blue.route('/follow')
@user_login_data
def follow():

    # 1,获取请求参数
    page = int(request.args.get("p",1))

    # 2,获取用户关注的人的分页对象
    paginate = g.user.followed.paginate(page,constants.FOLLOW_AUTHOR_COUNT,False)

    # 3,获取分页数据
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 4,封装数据渲染页面
    data = {
        "totalPage":totalPage,
        "currentPage":currentPage,
        "authors":[author.to_dict() for author in items]
    }
    return render_template('news/user_follow.html',data=data)

# 功能:个人新闻发布列表
@profile_blue.route('/news_list')
@user_login_data
def news_list():

    # 1,获取请求参数
    page = int(request.args.get("p",1))

    # 2,新闻分页查询
    paginate = g.user.news_list.order_by(News.create_time.desc()).paginate(page,constants.PUBLISH_NEWS_COUNT,False)

    # 3,获取分页数据
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 4,封装数据渲染页面
    data = {
        "totalPage":totalPage,
        "currentPage":currentPage,
        "news":items
    }
    return render_template('news/user_news_list.html',data=data)

# 功能:新闻发布
@profile_blue.route('/release',methods=["GET","POST"])
@user_login_data
def news_release():
    # 1,如果是get请求,展示新闻即可
    if request.method == "GET":
        data = {
            "categories":Category.query.all()
        }
        return render_template('news/user_news_release.html',data=data)

    # 2,如果是post请求,我们需要发布新闻了; 获取数据
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")

    # 3,数据校验(为空校验)
    if not all([title,category_id,digest,content,index_image]):
        return jsonify(errno=RET.NODATA,errmsg=error_map[RET.NODATA])

    # 4,图片上传
    index_image.name = f"news_content:{time.time()}{g.user.mobile}{index_image.name}"
    response = rest_upload(index_image)
    if not response:
        return jsonify(errno=RET.NODATA,errmsg=error_map[RET.NODATA])
    
    # 5,创建新闻对象,并设置属性
    news = News()
    news.title = title
    news.source = g.user.nick_name
    news.user_id = g.user.id
    news.digest = digest
    news.content = content
    news.index_image_url = constants.UPYUN_PREFIX + index_image.name
    news.category_id = category_id
    news.status = 1 # 表示新闻审核中
    
    # 6,添加新闻对象到数据库
    db.session.add(news)
    db.session.commit()

    # 7,返回响应
    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK])

# 功能:用户新闻收藏
@profile_blue.route('/collection')
@user_login_data
def collection():

    # 1,获取请求参数
    page = int(request.args.get("p","1"))

    # 2,分页查询用户收藏的新闻
    paginate = g.user.collection_news.paginate(page,constants.COLLECTION_NEWS_COUNT,False)

    # 3,获取到分页对象新闻数据
    totalPage = paginate.pages
    currentPage = paginate.page
    news = paginate.items

    # 4,封装data数据
    data = {
        "totalPage":totalPage,
        "currentPage":currentPage,
        "news":news
    }

    # 5,携带数据渲染页面
    return render_template('news/user_collection.html',data=data)

# 功能:密码修改
@profile_blue.route('/passwd_update',methods=["GET","POST"])
@user_login_data
def passwd_update():
    # 1,判断当前的请求是否GET, 如果是只需要渲染页面即可
    if request.method == "GET":
        return render_template("news/user_pass_info.html")

    # 2,如果当前的请求是POST,那么我们需要修改密码
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")
    new_password2 = request.json.get("new_password2")

    # 3,为空校验
    if not all([old_password,new_password,new_password2]):
        return jsonify(errno=RET.NODATA,errmsg=error_map[RET.NODATA])

    # 4,判断修改的新密码是否一致
    if new_password != new_password2:
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])

    # 5,判断老密码和新密码是否一致
    if g.user.check_password(new_password):
        return jsonify(errno=RET.REPWDERR,errmsg=error_map[RET.REPWDERR])

    # 6, 修改密码
    g.user.password = new_password
    db.session.commit()

    # 7,返回响应
    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK])

# 功能:头像设置
@profile_blue.route('/pic_info',methods=["GET","POST"])
@user_login_data
def user_pic_info():
    # 1,判断是否是get请求,如果是返回用户图片页面渲染
    if request.method == "GET":
        return render_template('news/user_pic_info.html',data={"user_info":g.user.to_dict()})

    # 2,如果是post请求,获取图片
    avatar = request.files.get("avatar")

    # 2,1 修改图片名称,免得多用户上传图片的时候,图片名称出现重复
    avatar.name = f"{time.time()}{g.user.mobile}{avatar.name}"

    # 3,将图片存储到本地
    # f = open('hello.png','wb')
    # f.write(avatar.read())
    # f.close()

    response = rest_upload(avatar)

    if not response:
        return jsonify(errno=RET.NODATA,errmsg=error_map[RET.NODATA])

    # 4,将地址更新到数据库
    g.user.avatar_url = avatar.name
    db.session.commit()

    # 5,返回响应
    data = {
        "avatar_url":constants.UPYUN_PREFIX + avatar.name
    }
    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK],data=data)

# 功能:基本资料
@profile_blue.route('/base_info',methods=["GET","POST"])
@user_login_data
def user_base_info():
    #1, 如果是一个get请求,直接渲染页面
    if request.method == "GET":
        return render_template('news/user_base_info.html',user_info=g.user.to_dict())

    #2, 如果是POST请求,证明需要修改基本信息,获取提交的用户信息
    signature = request.json.get("signature")
    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")

    #3,为空校验
    if not all([signature,nick_name,gender]):
        return jsonify(errno=RET.NODATA,errmsg=error_map[RET.NODATA])

    #4,性别校验(man,woman)
    if gender not in ["MAN","WOMAN"]:
        return jsonify(errno=RET.PARAMERR,errmsg=error_map[RET.PARAMERR])

    #5,修改用户信息
    g.user.signature = signature
    g.user.nick_name = nick_name
    g.user.gender = gender
    db.session.commit()

    #6,返回响应
    return jsonify(errno=RET.OK,errmsg=error_map[RET.OK])

# 功能: 个人中心页面展示
@profile_blue.route('/info')
@user_login_data
def user_info():
    # 1, 判断用户是否登录
    if not g.user:
        # 用户如果没有登录,重定向到首页
        return redirect("/")

    # 2,封装登录数据
    data = {
        "user_info":g.user.to_dict()
    }
    return render_template("news/user.html",data=data)